'''

Case Type： 套接字文件
Case Name： 套接字文件已存在启动数据库
Create At:  2020/06/29
Owner    :  n@ningyali
Descption:  1.从配置文件中获取套接字文件路径 2.获取套接字文件名 3.查看postmaster.pid中的pid 4.杀进程 5.启动数据库

'''

import os
import sys
import time
import unittest
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *


class SocketExistsStartDb(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case084.py start------------')
        self.pid_file_path = os.path.join(macro.DB_INSTANCE_PATH, macro.PID_FILE_NAME)
        self.dbUserNode = Node(node='dbuser')

    def test_socket_exists_start_db(self):
        self.log.info('----------------------------test1:套接字文件已存在启动数据库-----------------------------')
        # 从配置文件中获取套接字文件路径
        get_socket_dir_cmd = f"show unix_socket_directory;"
        self.log.info(get_socket_dir_cmd)
        msg = self.sh.executDbSql(get_socket_dir_cmd)
        self.log.info(msg)
        msg = msg.splitlines()
        socket_dir = msg[-2].strip()
        self.log.info(socket_dir)

        # 获取套接字文件名
        get_file_list_cmd = f'ls -a {socket_dir}'
        self.log.info(get_file_list_cmd)
        file_list = self.dbUserNode.sh(get_file_list_cmd).result()
        self.log.info(file_list)
        socket_file_name = ''
        for file in file_list.split():
            self.log.info(file)
            if (self.dbUserNode.db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file
        self.log.info(socket_file_name)

        # 查看postmaster.pid中的pid
        get_pid_cmd = f"cat {self.pid_file_path} | sed -n '1,1p'"
        self.log.info(get_pid_cmd)
        pid = self.dbUserNode.sh(get_pid_cmd).result()
        self.log.info(pid)
        self.assertIsNotNone(pid)

        # 杀进程
        kill_pid_cmd = f'kill -9 {pid.strip()}'
        self.log.info(kill_pid_cmd)
        msg = self.dbUserNode.sh(kill_pid_cmd).result()
        self.log.info(msg)
        self.assertEqual(msg, '')

        # 启动数据库
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

    def tearDown(self):
        self.log.info('------------Opengauss_Reliability_Dbsys_Case084:用例执行完毕--------------')
